<html>
    <script>

	var socketid;
	var stream;
	var pcs= {};

        // 与信令服务器的WebSocket连接
        //var socket = new WebSocket("wss://192.168.1.103:3000");
        var socket = new WebSocket("wss://deque.me:3000");

        // stun和turn服务器
        var iceServer = {
            "iceServers": [{
                "url": "stun:stun.l.google.com:19302"
            }, {
                "url": "turn:numb.viagenie.ca",
                "username": "webrtc@live.com",
                "credential": "muazkh"
            }]
        };

        //兼容浏览器的PeerConnection写法
        var PeerConnection = (window.PeerConnection ||
                            window.webkitPeerConnection00 || 
                            window.webkitRTCPeerConnection || 
                            window.mozRTCPeerConnection);

        var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

        getUserMedia.call(navigator, {
            video: true,
            audio: true
        }, function(localMediaStream) {
            var video = document.getElementById('localVideo');
            video.src = window.URL.createObjectURL(localMediaStream);
            video.onloadedmetadata = function(e) {
                console.log("Label: " + localMediaStream.label);
                console.log("AudioTracks" , localMediaStream.getAudioTracks());
                console.log("VideoTracks" , localMediaStream.getVideoTracks());
            };
	    stream = localMediaStream;
        }, function(e) {
            console.log('Reeeejected!', e);
        });


        //处理到来的信令
        socket.onmessage = function(event) {
            var json = JSON.parse(event.data);
            console.log('onmessage: ', json);
            //如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
            if( json.event === "_ice_candidate" ) {
		    pcs[json.data.socketid].addIceCandidate(new RTCIceCandidate(json.data.candidate));
            } else if (json.event == "_socket_id") {
		socketid = json.data.socketid;
		console.log(socketid);
            } else if (json.event == "_exit") {
		    var id = "other-" + json.data.socketid;
		    var element = document.getElementById(id);
		    element.parentNode.removeChild(element);
		    delete pcs[json.data.socketid];
            } else if(json.event === "_offer") {

			//创建PeerConnection实例
			var pc = new PeerConnection(iceServer);

			pcs[json.data.socketid] = pc;

			console.log("in _offer log pcs");
			console.log(pcs);

			// 发送ICE候选到其他客户端
			pc.onicecandidate = function(event){
				console.log(event.candidate);
			    if (event.candidate !== null) {
				socket.send(JSON.stringify({
				    "event": "_ice_candidate",
				    "data": {
					"candidate": event.candidate,
					"socketid": json.data.socketid
				    }
				}));
			    }
			};

			// 如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
			pc.onaddstream = function(event){
			    var newVideo = document.createElement("video"),
				id = "other-" + json.data.socketid;
			    newVideo.setAttribute("class", "other");
			    newVideo.setAttribute("autoplay", "autoplay");
			    newVideo.setAttribute("id", id);
			    newVideo.setAttribute("width", "320");
			    newVideo.setAttribute("height", "240");
			    videos.appendChild(newVideo);
			    document.getElementById(id).src = URL.createObjectURL(event.stream);
			};

		    //向PeerConnection中加入需要发送的流
		    pc.addStream(stream);

		    pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp));
		    pc.createAnswer( function(desc) {
			    pc.setLocalDescription(desc);
			    socket.send(JSON.stringify({ 
				    "event": "_answer",
				    "data": {
				 	   "sdp": desc,
					   "socketid":json.data.socketid
					   }
				  }));
		    },
		    function (error) {
			    console.log('Failure callback: ' + error);
		    });

	    }
        };
    </script>

<body>
  <div id="videos">
    <video width="320" height="240 "id="localVideo" autoplay></video><br>
  </div>
</body>

</html>
